// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case 'add_personal_donate': {
      return add_personal_donate(event, wxContext.OPENID);
    }
    case 'add_enterprise_donate': {
      return add_enterprise_donate(event, wxContext.OPENID);
    }
    case 'add_donated_materials': {
      return add_donated_materials(event, wxContext.OPENID);
    }
    case 'query_donated_materials': {
      return query_donated_materials(event, wxContext.OPENID);
    }
  }
}

/**
 * 查询捐赠单
 */
async function query_donated_materials(event, open_id) {
  var offset = event.offset ? event.offset : 0;
  var limit = event.limit ? event.limit : 10;
  var inTransit = event.in_transit != undefined ? event.in_transit : 1;
  var haveLogin = event.have_login != undefined? event.have_login : 0;
  var hospitalId = event.donate_hospital_id ? event.donate_hospital_id : -1;
  var filter = {};
  if (haveLogin == 1) {
    filter.user_id = open_id
  }
  if (inTransit == 1) {
    filter.logistics = _.neq(null)
  }
  if (hospitalId != -1) {
    filter.donate_hospital_id = event.donate_hospital_id
  }
  try {
    let response = await db.collection('donate_listing')
      .where(filter)
      .orderBy('updated_at', 'desc')
      .skip(offset)
      .limit(limit)
      .get({
        success: res => {
          return res
        },
        fail: err => {
          console.log(err)
        }
      })
    var list = response.data;
    var result = [];
    list.forEach(data => {
      let materials = data.materials;
      var title = '';
      if (materials) {
        for (let material in materials) {
          if (materials.length == 1) {
            title += materials[material].goods_name;
            break;
          }
          if (material == 1) {
            title += materials[material].goods_name + '...';
            break;
          } else {
            title += materials[material].goods_name + '、'
          }
        }
        data.title = title;
      }
      result.push(data);
    })
    response.data = result;
    return response;
  } catch(e) {
    console.log(e)
  }
}

/**
 * 生成捐赠清单
 */
async function add_donated_materials(event, open_id) {
  let donated_materials_info = {
    'user_id': open_id,
    /**
     * 捐赠方id 上一层获取
     */
    'donate_id': event.donate_id,
    /**
     * 捐赠方姓名
     */
    'donate_name': event.donate_name,
    /**
     * 捐赠的医院id
     */
    'donate_hospital_id': event.donate_hospital_id,
    /**
     * 捐赠的医院名
     */
    'donate_hospital_name': event.donate_hospital_name,
    /**
     * 捐赠物资
     * [{
     *  'goods_name': '医用防护口罩',
     *  'standard': 'GB 19083-2010',
     *  'amount': 1000,
     *  'supplier': '医疗机构'
     * }]
     */
    'materials': event.materials,
    /**
     * 物流信息
     * {
     *  'logistics_order': '2761537168',
     *  'logistics_company': '顺丰'
     * }
     */
    'logistics': event.logistics,
    /**
     * 捐赠说明
     */
    'content': event.content,
    'updated_at': new Date()
  }
  try {
    if (event._id) {
      return await db.collection('donate_listing')
        .doc(event._id)
        .update({
          data: donated_materials_info,
          success: res => {
            console.log("update success")
          },
          fail: err => {
            console.log("update error")
          }
        })
    } else {
      donated_materials_info.created_at = new Date();
      return await db.collection('donate_listing')
        .add({
          data: donated_materials_info,
          success: res => {
            console.log("insert success")
          },
          fail: err => {
            console.log("insert error")
          }
        })
    }
  } catch(e) {
    console.log(e)
  }
}

/**
 * 个人捐赠信息录入
 */
async function add_personal_donate(event, open_id) {
  let people_info = {
    'user_id':open_id,
    /**
     * 姓名
     */
    'name':event.name,
    /**
     * 身份证号码
     */
    'id_card':event.id_card,
    /**
     * 联系方式
     */
    'phone': event.phone,
    /**
     * 地址
     */
    'address':event.address,
    /**
     * 紧急联系人
     */
    'emergency_name':event.emergency_name,
    /**
     * 紧急联系人微信
     */
    'emergency_wechat':event.emergency_wechat,
    /**
     * 紧急联系人联系方式
     */
    'emergency_phone': event.emergency_phone,
    'created_at':new Date(),
    'updated_at':new Date(),
    'type':1
  }
  try {
    return await db.collection('donate')
      .add({
        data: people_info,
        success: res => {
          console.log("insert success")
        },
        fail: err => {
          console.log("insert error")
        }
      })
  } catch(e) {
    console.log(e)
  }
}

/**
 * 企业捐赠信息录入
 */
async function add_enterprise_donate(event, open_id) {
  let enterprise_info = {
    'user_id': open_id,
    /**
     * 企业名称
     */
    'enterprise_name': event.enterprise_name,
    /**
     * 企业组织代码
     */
    'enterprise_code': event.enterprise_code,
    /**
     * 企业联系人
     */
    'enterprise_contact': event.enterprise_contact,
    /**
     * 联系方式
     */
    'enterprise_phone': event.enterprise_phone,
    /**
     * 公司地址
     */
    'enterprise_address': event.enterprise_address,
    /**
     * 紧急联系人
     */
    'emergency_contact': event.emergency_contact,
    /**
     * 紧急联系人微信
     */
    'emergency_wechat': event.emergency_wechat,
    /**
     * 紧急联系人联系方式
     */
    'emergency_phone': event.emergency_phone,
    'created_at': new Date(),
    'updated_at': new Date(),
    'type': 2
  }
  try {
    return await db.collection('donate')
      .add({
        data: enterprise_info,
        success: res => {
          console.log("insert success")
        },
        fail: err => {
          console.log("insert error")
        }
      })
  } catch (e) {
    console.log(e)
  }
}